<template>
  <div class="cart" v-loading="loading">
    <el-card>
      <div class="top-title">
        <p class="title">我的购物清单</p>
        <p class="info">挣钱很累，理性消费！Y优购虔诚为你服务！！！</p>
      </div>
      <div class="clear" v-if="isshow">
        <el-link :underline="false" @click="delItem">清空购物车</el-link>
      </div>
      <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        @select-all="handleallChange"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column label="图片" width="240">
          <template slot-scope="scope">
            <el-image :src="scope.row.thumb_url">
              <div slot="placeholder" class="image-slot">
                加载中<span class="dot">...</span>
              </div>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="goods_name" label="商品名"> </el-table-column>
        <el-table-column prop="goods_price" label="价格" show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="数量" show-overflow-tooltip>
          <template> 1件 </template>
        </el-table-column>
        <el-table-column prop="goods_price" label="小计" show-overflow-tooltip>
        </el-table-column>
      </el-table>
<hr>
<!-- 失效订单 -->
<div class="miss-box" v-if="tableData1.length !==0">
<p class="miss"> <el-link type="warning" :underline="false">已失效商品</el-link><el-link v-show="multipleSelection1.length" type="warning" :underline="false" @click="deleMiss">删除{{multipleSelection1.length}}件失效商品</el-link></p>
<el-table
        :cell-style="misscover"
        :show-header="false"
        ref="multipleTable1"
        :data="tableData1"
        tooltip-effect="dark"
        @selection-change="handleSelectionChange1"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column label="图片" width="240">
          <template slot-scope="scope">
            <el-image :src="scope.row.thumb_url">
              <div slot="placeholder" class="image-slot">
                加载中<span class="dot">...</span>
              </div>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="goods_name" label="商品名"> </el-table-column>
        <el-table-column prop="goods_price" label="价格" show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="数量" show-overflow-tooltip>
          <template> 0件 </template>
        </el-table-column>
        <el-table-column  label="状态" show-overflow-tooltip>
          此商品已售空
        </el-table-column>
      </el-table>
</div>
      <div class="settlement-box">
        <el-button
          v-show="isshowitem"
          type="danger"
          icon="el-icon-delete"
          @click="delItem"
          size="mini"
          >删除{{ multipleSelection.length }}个商品</el-button
        >
        <p>
          商品金额总计：￥<span>{{ allPrice }}</span>
        </p>
        <p><el-button type="warning" @click="buyItem">提交订单</el-button></p>
      </div>
    </el-card>
    <el-dialog title="商品订单" :visible.sync="ishowOrder" center >
      <el-form label-width="120px" :inline="true" :model="orderForm" :rules="orderRules" ref="orderFormRef">
            <el-form-item label="收货人" prop="accountName">
              <el-input v-model="orderForm.accountName" :maxlength="11" placeholder="请填写收货人姓名" autocomplete clearable></el-input>
            </el-form-item>
             <el-form-item label="手机号码" prop="phone">
              <el-input v-model="orderForm.phone" autocomplete  placeholder="请填写收货人手机号" clearable>
              </el-input>
            </el-form-item>
            <el-form-item label="所在地区" prop="address1">
<el-cascader :options="cityData" :props="{ expandTrigger: 'hover' }" v-model="orderForm.address1"></el-cascader>
            </el-form-item>
           
			<el-form-item prop="address2" label="详细地址">
			    <el-input type="textarea"
   v-model="orderForm.address2" placeholder="请填写街道、楼牌号等"></el-input>
			</el-form-item>
            
          </el-form>

  <el-table
        ref="multipleTable2"
        :data="finalOrders"
        tooltip-effect="dark"
      >
        <el-table-column type="index" width="50"> </el-table-column>
        <el-table-column label="图片" width="100">
          <template slot-scope="scope">
            <el-image :src="scope.row.thumb_url">
              <div slot="placeholder" class="image-slot">
                加载中<span class="dot">...</span>
              </div>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="goods_name" label="商品名" show-overflow-tooltip> </el-table-column>
        <el-table-column prop="goods_price" label="价格" show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="数量" show-overflow-tooltip>
          <template> 1件 </template>
        </el-table-column>
        <el-table-column prop="goods_price" label="小计" show-overflow-tooltip>
        </el-table-column>
      </el-table>
      <p style="text-align: right;">
          商品金额总计：￥<span style="color:#f8b81e;font-size: 20px;">{{ finalPrice }}</span>
        </p>
         <span slot="footer" class="dialog-footer">
    <el-button @click="ishowOrder = false">取 消</el-button>
    <el-button type="primary" @click="submitOrder">确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>

<script>
import cityData from '../util/citydata.js'
import { seeCartByid, delItems, payItem,getfinorderList } from "network/request.js";
export default {
  data() {
      const checkPhone = (rule, value, cb) => {
      // 验证手机号正则表达式
      const regPhone = /^(0|86|17951)?(13[0-9]|15[012356789]|17[789]|18[0-9]|14[57])[0-9]{8}$/;

      if (regPhone.test(value)) {
        // 合法手机号
        return cb();
      }
      // 非法邮箱
      cb(new Error("请输入合法的手机号"));
    };
    return {
        orderRules: {
        accountName: [{ required: true, message: "请填写收货人", trigger: "blur" }],
        phone: [
          { required: true, message: "请填写收货人手机号", trigger: "blur" },
          { validator: checkPhone, trigger: "blur" }
        ],
		    address1: [{required: true, message: "请选择所属地区", trigger: "blur" }],
		    address2: [{required: true, message: "请填写具体收货地址", trigger: "blur" }],

      },
      orderForm: {
        accountName:'',
        phone:'',
        address1:'',
        address2:''
      },
      cityData,
      ishowOrder: false,
          loading: false,
      isshowitem: false,
      isshow: false,
      maxlengthes: 0,
      allPrice: 0,
      tableData: [],
      tableData1:[],
      tableData2: [],
      multipleSelection: [],
      multipleSelection1: [],
      // 最终订单
      finalOrders: [],
      // 最终价格
      finalPrice:0
    };
  },
  created() {
	    this.getlist();
  },
  methods: {
    // 失效颜色
    misscover(){
      return '  background: #eee'
    },
    // 结算账单
    submitOrder(){
       this.$confirm("确定支付购买吗?", "提示", {
        confirmButtonText: "确定支付",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
           this.$refs.orderFormRef.validate(async (valid) => {
        if (!valid) {
          this.$message.error("请填写必要的收货地址！");
        } else if(this.finalOrders.length == 0){
            this.$message.warning('您所购买的商品已售空，请选购其他商品！');
            this.getlist();
        } else {
            this.loading =true;
          let newarr = this.finalOrders.map((item, index) => {
            return {
              goods_id: item.goods_id,
              user_id: window.sessionStorage.getItem("uid"),
              accountName: this.orderForm.accountName,
              phone: this.orderForm.phone,
              address1: this.orderForm.address1.join(''),
              address2: this.orderForm.address2,
            };
          });
          const res = await payItem(newarr);
          if (res.status === 200) {
            this.$message.success("已成功购买，请注意订单信息！");
          this.loading =false;
          this.ishowOrder =false;
            this.delItem();
          }
        }
        })
        .catch(() => {
          this.getlist();
        }); 
        })
    },
    // 提交订单
    buyItem() {
      if(this.multipleSelection.length == 0) {
        this.$message.warning('请选中将要购买的商品！')
      } else {
        this.ishowOrder = true
         this.getfinlist()
     
      }
    },
    // 失效选择触发
    handleSelectionChange1(val) {
      console.log(val);
     this.multipleSelection1 = val
    },
    // 全选触发
    handleallChange(val) {
      if (val.length == this.maxlengthes) {
        this.isshow = true;
      } else {
        this.isshow = false;
      }
    },
    // 选择触发
    handleSelectionChange(val) {
      if (val.length == this.maxlengthes) {
        this.isshow = true;
      } else {
        this.isshow = false;
      }
      if (val.length > 0) {
        this.isshowitem = true;
      } else {
        this.isshowitem = false;
      }
      this.multipleSelection = val;
      console.log(val);
      this.allPrice = val.reduce(
        (accumulator, cur) => accumulator + cur.goods_price,
        0
      );
    },
    //   请求数据获取购物车列表
    async getlist() {
      const { data: res } = await seeCartByid({
        user_id: window.sessionStorage.getItem("uid"),
      });
      console.log(res);
      this.tableData= res.filter(item => item.buystatus == 0)
     this.tableData1= res.filter(item => item.buystatus == 1)
      this.maxlengthes = this.tableData.length;
      if (res.length == 0) {
        this.isshow = false;
      }
    },

    // 确认订单申请最终商品
    async getfinlist() {
      let newarr = [];
      this.multipleSelection.forEach((item, index) => {
        newarr.push(item.goods_id);
      });
     const {data: res} = await getfinorderList(newarr);
     this.finalOrders = res
     this.finalPrice = res.reduce(
        (accumulator, cur) => accumulator + cur.goods_price,
        0
      );
      if(this.finalOrders.length == 0) {
        this.$message.warning('当前商品已售空，请重新选择！')
      }
     console.log(res);

      // this.getlist()
    },
    // 删除
    async delItem() {
     
    let newarr = [];
      this.multipleSelection.forEach((item, index) => {
        newarr.push(item.goods_id);
      });
      console.log(newarr);
      const res = await delItems({
        newarr,
        user_id: window.sessionStorage.getItem("uid"),
      });
      console.log(res);
      if (res.status === 200) {
        this.isshow = false
         
        this.getlist();
      }    
  
    },
    // 删除失效订单
    async deleMiss() {
        let newarr = [];
      this.multipleSelection1.forEach((item, index) => {
        newarr.push(item.goods_id);
      });
      console.log(newarr);
      const res = await delItems({
        newarr,
        user_id: window.sessionStorage.getItem("uid"),
      });
      console.log(res);
      if (res.status === 200) {
        this.getlist();
      }
    }
  },
};
</script>

<style lang="scss" scoped>
.el-table .misscolor {
  background-color: #aaa;
}
.cart {
  min-height: 800px;
  padding-top: 60px;
  .top-title {
    padding: 50px 20px;
    .title {
      font-size: 30px;
      font-weight: bold;
    }
    .info {
      padding: 10px 20px;
    }
  }
  .clear {
    background-color: #eee;
    text-align: center;
    
  }
  .miss {
    padding: 10px 20px;
    display: flex;
    justify-content: space-between;
  }
  .el-table {
    width: 70%;
    margin: 0 auto;
  }
  .settlement-box {
    width: 100%;
    text-align: right;
    p {
      font-size: 20px;
      padding: 10px 10px;
      span {
        font-size: 25px;
        color: #f8b81e;
      }
    }
  }
}
</style>>
